<?php
/**
 * @param $var
 *
 * debug函数
 */
function p ( $var )
{
    echo "<pre>";
    print_r( $var );
    echo "</pre>";
}

/**
 * @param      $url
 * @param null $param
 * @param bool $is_file
 * @param bool $return_array
 *
 * @return mixed|string
 *
 * 以POST方式提交数据
 */
function post_data ( $url , $param = NULL , $is_file = FALSE , $return_array = TRUE )
{
    set_time_limit( 0 );
    if ( !$is_file && is_array( $param ) ) {
        $param = JSON( $param );
    }

    if ( $is_file ) {
        $header [] = "content-type: multipart/form-data; charset=UTF-8";
    } else {
        $header [] = "content-type: application/json; charset=UTF-8";
    }
    $ch = curl_init();
    //    if ( class_exists( '/CURLFile' ) ) { // php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的默认值不同
    //        curl_setopt( $ch , CURLOPT_SAFE_UPLOAD , TRUE );
    //    } else {
    //        if ( defined( 'CURLOPT_SAFE_UPLOAD' ) ) {
    //            curl_setopt( $ch , CURLOPT_SAFE_UPLOAD , FALSE );
    //        }
    //    }
    curl_setopt( $ch , CURLOPT_URL , $url );
    curl_setopt( $ch , CURLOPT_CUSTOMREQUEST , "POST" );
    curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , FALSE );
    curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , FALSE );
    curl_setopt( $ch , CURLOPT_HTTPHEADER , $header );
    curl_setopt( $ch , CURLOPT_USERAGENT , 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
    curl_setopt( $ch , CURLOPT_FOLLOWLOCATION , 1 );
    curl_setopt( $ch , CURLOPT_AUTOREFERER , 1 );
    curl_setopt( $ch , CURLOPT_POSTFIELDS , $param );
    curl_setopt( $ch , CURLOPT_RETURNTRANSFER , TRUE );
    $res = curl_exec( $ch );
    $flat = curl_errno( $ch );
    if ( $flat ) {

        $data = curl_error( $ch );

        return "curl出错，错误码:$data";
    }
    curl_close( $ch );

    $return_array && $res = json_decode( $res , TRUE );

    return $res;
}

/**
 * @param $url
 *
 * @return mixed|string
 *
 * get请求
 */
function get_data ( $url )
{
    //初始化
    $ch = curl_init();

    //设置选项，包括URL
    curl_setopt( $ch , CURLOPT_URL , $url );
    curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
    curl_setopt( $ch , CURLOPT_HEADER , 0 );

    //执行并获取HTML文档内容
    $output = curl_exec( $ch );

    $flat = curl_errno( $ch );
    if ( $flat ) {

        $data = curl_error( $ch );

        return "curl出错，错误码:$data";
    }
    curl_close( $ch );

    $res = json_decode( $output , TRUE );

    return $res;
}

/**
 * ************************************************************
 *
 * 将数组转换为JSON字符串（兼容中文）
 *
 * @param array $array
 *            要转换的数组
 *
 * @return string 转换得到的json字符串
 * @access public
 *
 * ***********************************************************
 */
function JSON ( $array )
{
    arrayRecursive( $array , 'urlencode' , TRUE );
    $json = json_encode( $array );

    return urldecode( $json );
}

/**
 * ************************************************************
 *
 * 使用特定function对数组中所有元素做处理
 *
 * @param
 *            string &$array 要处理的字符串
 * @param string $function
 *            要执行的函数
 *
 * @return boolean $apply_to_keys_also 是否也应用到key上
 * @access public
 *
 * ***********************************************************
 */
function arrayRecursive ( &$array , $function , $apply_to_keys_also = FALSE )
{
    static $recursive_counter = 0;
    if ( ++$recursive_counter > 1000 ) {
        die ( 'possible deep recursion attack' );
    }
    foreach ( $array as $key => $value ) {
        if ( is_array( $value ) ) {
            arrayRecursive( $array [ $key ] , $function , $apply_to_keys_also );
        } else {
            $array [ $key ] = $function ( $value );
        }

        if ( $apply_to_keys_also && is_string( $key ) ) {
            $new_key = $function ( $key );
            if ( $new_key != $key ) {
                $array [ $new_key ] = $array [ $key ];
                unset ( $array [ $key ] );
            }
        }
    }
    $recursive_counter--;
}

/**
 * @param $data
 *
 * @return mixed 加密数据解码  $iv,$code是被加密过的数据，由于请求过程中因为编码原因+号变成了空格，所以我们需要用下面的方法转换回来
 */
function define_str_replace ( $data )
{
    return str_replace( ' ' , '+' , $data );
}

/**
 * @param $object
 *
 * @return array
 *
 * 对象转数组
 */
function object2array ( $object )
{
    $array = [];
    if ( is_object( $object ) ) {
        foreach ( $object as $key => $value ) {
            $array[ $key ] = $value;
        }
    } else {
        $array = $object;
    }

    return $array;
}

/**
 * @param $mobile
 *
 * @return int
 *
 * 判断是否为合法的身份证号码
 */
function isCreditNo ( $vStr )
{
    $vCity = [
        '11' ,
        '12' ,
        '13' ,
        '14' ,
        '15' ,
        '21' ,
        '22' ,
        '23' ,
        '31' ,
        '32' ,
        '33' ,
        '34' ,
        '35' ,
        '36' ,
        '37' ,
        '41' ,
        '42' ,
        '43' ,
        '44' ,
        '45' ,
        '46' ,
        '50' ,
        '51' ,
        '52' ,
        '53' ,
        '54' ,
        '61' ,
        '62' ,
        '63' ,
        '64' ,
        '65' ,
        '71' ,
        '81' ,
        '82' ,
        '91' ,
    ];
    if ( !preg_match( '/^([\d]{17}[xX\d]|[\d]{15})$/' , $vStr ) ) {
        return FALSE;
    }
    if ( !in_array( substr( $vStr , 0 , 2 ) , $vCity ) ) {
        return FALSE;
    }
    $vStr = preg_replace( '/[xX]$/i' , 'a' , $vStr );
    $vLength = strlen( $vStr );
    if ( $vLength == 18 ) {
        $vBirthday = substr( $vStr , 6 , 4 ) . '-' . substr( $vStr , 10 , 2 ) . '-' . substr( $vStr , 12 , 2 );
    } else {
        $vBirthday = '19' . substr( $vStr , 6 , 2 ) . '-' . substr( $vStr , 8 , 2 ) . '-' . substr( $vStr , 10 , 2 );
    }
    if ( date( 'Y-m-d' , strtotime( $vBirthday ) ) != $vBirthday ) {
        return FALSE;
    }
    if ( $vLength == 18 ) {
        $vSum = 0;
        for ( $i = 17; $i >= 0; $i-- ) {
            $vSubStr = substr( $vStr , 17 - $i , 1 );
            $vSum += ( pow( 2 , $i ) % 11 ) * ( ( $vSubStr == 'a' ) ? 10 : intval( $vSubStr , 11 ) );
        }
        if ( $vSum % 11 != 1 ) {
            return FALSE;
        }
    }

    return TRUE;
}

/**
 * @param $cid
 *
 * @return int|string 1男 2女
 *
 * 根据身份证号，自动返回性别
 */
function getSexByCard ( $cid )
{
    if ( !isCreditNo( $cid ) ) {
        return 0;
    }
    $sexInt = (int)substr( $cid , 16 , 1 );

    return $sexInt % 2 === 0 ? 2 : 1;
}

/**
 * 把全名拆分为姓氏和名字
 *
 * @param string $fullName 全名
 *
 * @return array 一维数组,元素一是姓,元素二为名
 */
function splitName ( $fullName )
{

    $hyphenated = [
        '欧阳' ,
        '太史' ,
        '端木' ,
        '上官' ,
        '司马' ,
        '东方' ,
        '独孤' ,
        '南宫' ,
        '万俟' ,
        '闻人' ,
        '夏侯' ,
        '诸葛' ,
        '尉迟' ,
        '公羊' ,
        '赫连' ,
        '澹台' ,
        '皇甫' ,
        '宗政' ,
        '濮阳' ,
        '公冶' ,
        '太叔' ,
        '申屠' ,
        '公孙' ,
        '慕容' ,
        '仲孙' ,
        '钟离' ,
        '长孙' ,
        '宇文' ,
        '城池' ,
        '司徒' ,
        '鲜于' ,
        '司空' ,
        '汝嫣' ,
        '闾丘' ,
        '子车' ,
        '亓官' ,
        '司寇' ,
        '巫马' ,
        '公西' ,
        '颛孙' ,
        '壤驷' ,
        '公良' ,
        '漆雕' ,
        '乐正' ,
        '宰父' ,
        '谷梁' ,
        '拓跋' ,
        '夹谷' ,
        '轩辕' ,
        '令狐' ,
        '段干' ,
        '百里' ,
        '呼延' ,
        '东郭' ,
        '南门' ,
        '羊舌' ,
        '微生' ,
        '公户' ,
        '公玉' ,
        '公仪' ,
        '梁丘' ,
        '公仲' ,
        '公上' ,
        '公门' ,
        '公山' ,
        '公坚' ,
        '左丘' ,
        '公伯' ,
        '西门' ,
        '公祖' ,
        '第五' ,
        '公乘' ,
        '贯丘' ,
        '公皙' ,
        '南荣' ,
        '东里' ,
        '东宫' ,
        '仲长' ,
        '子书' ,
        '子桑' ,
        '即墨' ,
        '达奚' ,
        '褚师' ,
    ];

    $vLength = mb_strlen( $fullName , 'utf-8' );

    $lastName = '';

    $firstName = '';//前为姓,后为名

    if ( $vLength > 2 ) {
        $preTwoWords = mb_substr( $fullName , 0 , 2 , 'utf-8' );//取命名的前两个字,看是否在复姓库中
        if ( in_array( $preTwoWords , $hyphenated ) ) {
            $lastName = $preTwoWords;
            $firstName = mb_substr( $fullName , 2 , 10 , 'utf-8' );
        } else {
            $lastName = mb_substr( $fullName , 0 , 1 , 'utf-8' );
            $firstName = mb_substr( $fullName , 1 , 10 , 'utf-8' );
        }
    } else if ( $vLength == 2 ) {//全名只有两个字时,以前一个为姓,后一下为名
        $lastName = mb_substr( $fullName , 0 , 1 , 'utf-8' );
        $firstName = mb_substr( $fullName , 1 , 10 , 'utf-8' );
    } else {
        $lastName = $fullName;
    }

    return [ $lastName , $firstName ];
}

/**
 * @param array $urlObj
 *
 * @return string
 *
 * 参数数组转换为url参数
 */
function toUrlParams ( array $urlObj )
{
    $buff = "";
    foreach ( $urlObj as $k => $v ) {
        if ( !is_array( $k ) && !is_array( $v ) ) {
            if ( preg_match( "/[\x7f-\xff]/" , $v ) ) {
                $v = urlencode( $v );
            }
            $buff .= $k . "=" . $v . "&";
        } elseif ( $k == 'filter' && is_array( $v ) ) {
            $buff .= $k . "=";
            foreach ( $v as $key => $value ) {
                if ( $key != 'entity_names' ) {
                    $buff .= $key . ":" . $value . "|";
                } else {
                    $buff .= $key . ":" . implode( ',' , $value ) . "|";
                }
            }
            $buff = trim( $buff , "|" );
        }
    }
    $buff = trim( $buff , "&" );

    return $buff;
}

/**
 * @param $url
 * @param $params
 *
 * @return mixed|string
 *
 * post请求
 */
function post ( $url , $params )
{
    $arr = toUrlParams( $params );

    $curl = curl_init();

    curl_setopt_array( $curl , [
        CURLOPT_URL            => $url ,
        CURLOPT_RETURNTRANSFER => TRUE ,
        CURLOPT_ENCODING       => "" ,
        CURLOPT_MAXREDIRS      => 10 ,
        CURLOPT_TIMEOUT        => 30 ,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1 ,
        CURLOPT_CUSTOMREQUEST  => "POST" ,
        CURLOPT_POSTFIELDS     => $arr ,
        CURLOPT_HTTPHEADER     => [
            "cache-control: no-cache" ,
            "content-type: application/x-www-form-urlencoded" ,
        ] ,
    ] );

    $response = curl_exec( $curl );
    $err = curl_error( $curl );

    curl_close( $curl );

    if ( $err ) {
        return "cURL Error #:" . $err;
    } else {
        return json_decode( $response );
    }
}

/**
 * @param $timestamp
 *
 * @return string
 *
 * 根据时间戳返回人类可读的时间格式
 */
function getTimeText ( $timestamp )
{
    $h = date( 'G' , $timestamp );

    if ( $h > 6 && $h <= 11 ) {
        $str = '早上';
    } else if ( $h > 11 && $h <= 13 ) {
        $str = '中午';
    } else if ( $h > 13 && $h <= 18 ) {
        $str = '下午';
    } else if ( $h > 18 && $h <= 24 ) {
        $str = '晚上';
    } else {
        $str = '凌晨';
    }

    $todayEnd = strtotime( date( 'Ymd' ) ) + 86400;

    if ( $timestamp >= $todayEnd ) {
        $str = date( 'd号' , $timestamp ) . $str;
    }

    if ( substr( date( 'gi' , $timestamp ) , -2 ) == '00' ) {
        $str .= date( 'g点' , $timestamp );
    } else {
        $str .= date( 'g点i分' , $timestamp );
    }

    return $str;
}

/**
 * @param int $length
 *
 * @return string
 *
 * 随机字符串
 */
function generateRandomString ( $length = 32 )
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str = '';
    for ( $i = 0; $i < $length; $i++ ) {
        $str .= $chars[ mt_rand( 0 , strlen( $chars ) - 1 ) ];
    }

    return $str;
}

/**
 * @param $url
 *
 * @return bool|int
 *
 * 检测网址是否有效
 */
function url_exists ( $url )
{
    $headers = @get_headers( $url );

    return is_array( $headers ) ? preg_match( '/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/' , $headers[ 0 ] ) : FALSE;
}

/**
 * @param $data
 * @param $method
 *
 * email的形式发送debug
 */
function emailDebug ( $data , $method )
{
    Yii::info( $data , $method );
}